<template>
  <view class="chat-container">
    <view class="tab-container">
      <swiper class="sw">
        <swiper-item
          v-for="(item, index) in list"
          :key="item.id"
          class="sw-item"
        >
          <view
            :class="[index == current ? 'active-color' : 'nomal-color']"
            @click.stop="tabClick(index, item.id)"
          >
            {{ item.name }}
          </view>
        </swiper-item>
      </swiper>
    </view>
    <wechat-list :historys="historys" @doCollect="doLoves"></wechat-list>
  </view>
</template>

<script>
import { histories, wxcharts, collectArciles, uncollected } from "@/api/api.js";
export default {
  data() {
    return {
      list: [],
      current: 0,
      pageIndex: 1,
      id: "",
      historys: [],
    };
  },
  onLoad(opts) {
    this.fetchList();
  },
  onPullDownRefresh() {
    this.historys = [];
    this.pageIndex = 1;
    this.fetHisList();
    uni.stopPullDownRefresh();
  },
  onReachBottom() {
    this.pageIndex++;
    this.fetHisList();
  },
  methods: {
    doLoves(index, isCollect) {
      let id = this.historys[index].id;

      if (isCollect) {
        //取消收藏
        this.cancleCollects(id);
      } else {
        //添加收藏
        this.addCollects(id, this.historys[index]);
      }
      this.$set(this.historys[index], "collect", !isCollect);
    },
    async cancleCollects(id) {
      let rs = await uncollected(id);
      if (rs.errorCode == 0) {
        uni.showToast({
          title: "取消收藏",
          icon: "none",
        });
      }
    },
    async addCollects(id, obj) {
      let rs = await collectArciles(id);

      if (rs.errorCode == 0) {
        uni.showToast({
          title: "收藏成功",
          icon: "none",
        });
      }
    },
    async fetHisList() {
      let res = await histories(this.id, this.pageIndex);

      this.historys = this.historys.concat(res.data.datas);
    },
    async fetchList() {
      let res = await wxcharts();
      this.list = res.data;
      this.id = this.list[0].id;
      this.fetHisList();
    },
    change(index) {
      this.current = index;
    },
    tabClick(index, id) {
      this.current = index;
      this.id = id;
      this.pageIndex = 1;
      this.historys = [];

      this.fetHisList();
    },
  },
};
</script>
<style lang="scss" scoped>
.active-color {
  color: green;
  font-size: 32rpx;
  border-bottom: 1px solid green;
}

.nomal-color {
  color: black;
  font-size: 30rpx;
}

.chat-container {
  .tab-container {
    .sw {
      height: 100rpx;

      .sw-item {
        width: 220rpx !important;

        > view {
          padding: 16rpx;
          display: inline-block;
        }
      }
    }
  }
}
</style>
